package com.wordpress.letssmileagain.www.googlestt;
import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognitionService;
import android.speech.RecognizerIntent;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static android.R.attr.data;
import static android.R.id.message;
/***
 * @Copyright OM Bharatiya
 *
 */


public class MainActivity extends AppCompatActivity {
    private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
    private static final String TAG = "STT test";
    private Constants.State mState;
    TextView txtView;
    ArrayList<String> result = null;
    ImageView mic, wp, twtr, more;
    private Resources mRes;
    private SharedPreferences mPrefs;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtView  = (TextView) findViewById(R.id.textView);
        mic = (ImageView) findViewById(R.id.mic);
        wp = (ImageView) findViewById(R.id.whatsapp);
        twtr = (ImageView) findViewById(R.id.twitter);
        more = (ImageView) findViewById(R.id.more);
        mRes = getResources();
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        mic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(),"Say Something...",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                //intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
                intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
                intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
                intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getApplicationContext().getPackageName());

                // Start listening for speech input
                if(speechRecognizer!=null) {
                    speechRecognizer.startListening(intent);
                }
                else {
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivityForResult(intent, 5);
                    } else {
                        Toast.makeText(v.getContext(), "Your Device Doesn't Support Speech Intent", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });

        wp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) throws NullPointerException {
                if(result!=null) {
                    Toast.makeText(v.getContext(),"To whatsapp...",Toast.LENGTH_SHORT).show();
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
//                    Log.e("JUST FOR TESTING",result.get(0));
                    sendIntent.putExtra(Intent.EXTRA_TEXT, result.get(0));
                    sendIntent.setType("text/plain");
                    sendIntent.setPackage("com.whatsapp");
                    startActivity(sendIntent);
                }
                else{
                    Toast.makeText(v.getContext(),"First Say Something in the Mic!!",Toast.LENGTH_SHORT).show();
                }
            }
        });

        twtr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(result!=null) {
                    Intent tweetIntent = new Intent(Intent.ACTION_SEND);
                    tweetIntent.putExtra(Intent.EXTRA_TEXT, result.get(0));
                    tweetIntent.setType("text/plain");

                    PackageManager packManager = getPackageManager();
                    List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

                    boolean resolved = false;
                    for (ResolveInfo resolveInfo : resolvedInfoList) {
                        if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
                            tweetIntent.setClassName(
                                    resolveInfo.activityInfo.packageName,
                                    resolveInfo.activityInfo.name);
                            resolved = true;
                            break;
                        }
                    }
                    if (resolved) {
                        startActivity(tweetIntent);
                    } else {
                        Intent i = new Intent();
                        i.putExtra(Intent.EXTRA_TEXT, result.get(0));
                        i.setAction(Intent.ACTION_VIEW);
                        i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode(result.get(0))));
                        startActivity(i);
                        Toast.makeText(v.getContext(), "Twitter app isn't found", Toast.LENGTH_LONG).show();
                    }
                }
                else {
                    Toast.makeText(v.getContext(),"First Say Something in the Mic!!",Toast.LENGTH_SHORT).show();
                }
            }
        });

        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(result!=null) {
                    Toast.makeText(v.getContext(),"Choose an app...",Toast.LENGTH_SHORT).show();
                    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                    sharingIntent.setType("text/plain");
                    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, result.get(0).substring(0, 10));
                    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, result.get(0));
                    startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using)));


                }
                else {
                Toast.makeText(v.getContext(),"First Say Something in the Mic!!",Toast.LENGTH_SHORT).show();
                }

            }
        });
        // check for permission
        int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
            return;
        }
        context = getApplicationContext();
  // Check if the device supports speech recognition
        if (!android.speech.SpeechRecognizer.isRecognitionAvailable(context)) {
            Toast.makeText(context, "Your Device Doesn't Support Speech Intent", Toast.LENGTH_SHORT).show();
                String appPackageName = "com.google.android.googlequicksearchbox";
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("market://details?id=" + appPackageName)));
                } catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                }

        }

            // Create a SpeechRecognizer instance
        //speechRecognizer = android.speech.SpeechRecognizer.createSpeechRecognizer(context);
        //speechRecognizer = android.speech.SpeechRecognizer.createSpeechRecognizer(context, ComponentName.unflattenFromString("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"));
        speechRecognizer = android.speech.SpeechRecognizer.createSpeechRecognizer(context, ComponentName.unflattenFromString("com.google.android.tts/com.google.android.apps.speech.tts.googletts.service.GoogleTTSRecognitionService"));
            // Set up a RecognitionListener to handle speech recognition events
        if(speechRecognizer!=null){
        speechRecognizer.setRecognitionListener(new android.speech.RecognitionListener() {

            @Override
                public void onReadyForSpeech(Bundle params) {
                    // Called when the speech recognition service is ready to receive speech input.
                    Log.d(TAG, "onReadyForSpeech");
                    mState = Constants.State.RECORDING;
                }

                @Override
                public void onBeginningOfSpeech() {
                    // Called when the user starts speaking.
                    Log.d(TAG, "onBeginningOfSpeech");
                    mState = Constants.State.LISTENING;
                }

                @Override
                public void onRmsChanged(float v) {
                    Log.d(TAG, "onRmsChanged");
                }

                @Override
                public void onBufferReceived(byte[] bytes) {
                    Log.d(TAG, "onBufferReceived");
                }

                @Override
                public void onEndOfSpeech() {
                    // Called when the user stops speaking.
                    Log.d(TAG, "onEndOfSpeech");
                    mState = Constants.State.TRANSCRIBING;
                }

                @Override
                public void onError(int error) {
                    mState = Constants.State.ERROR;
                    // Called when an error occurs during speech recognition.
                    speechRecognizer.stopListening();
                    Log.d(TAG, "onError");
                }

                @Override
                public void onResults(Bundle results) {
                    Log.d(TAG, "onResults");

                    // Called when speech recognition successfully recognizes speech.
                    // Retrieve the recognized text from the results.
                    ArrayList<String> voiceResults = results.getStringArrayList(android.speech.SpeechRecognizer.RESULTS_RECOGNITION);
                    if (voiceResults != null && !voiceResults.isEmpty()) {
                        String recognizedText = voiceResults.get(0);
                        // Handle the recognized text as needed.
                        txtView.setText(recognizedText);
                    }
                    speechRecognizer.stopListening();
                    mState = Constants.State.INIT;

                }

                @Override
                public void onPartialResults(Bundle partialResults) {
                   Log.d(TAG, "onPartialResults");
                    // This is supported (only?) by Google Voice Search.
                    // The following is Google-specific.
                    Log.i(TAG,"onPartialResults: keySet: " +partialResults.keySet().toString());
                    String[] results = partialResults.getStringArray("com.google.android.voicesearch.UNSUPPORTED_PARTIAL_RESULTS");
                    //double[] resultsConfidence = partialResults.getDoubleArray("com.google.android.voicesearch.UNSUPPORTED_PARTIAL_RESULTS_CONFIDENCE");
                    if (results != null) {
                             txtView.setText(TextUtils.join(" · ", results));
                    }
                }

                @Override
                public void onEvent(int i, Bundle bundle) {
                    Log.d(TAG, "onEvent");
                }

                // Other methods for handling partial results, onPartialResults, onEvent, etc.
            });


        }


    }

    private String urlEncode(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.v("UTF ENCODING EXCEPTION", "UTF-8 should always be supported", e);
            return "";
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==5) {
            if(resultCode==RESULT_OK && data!=null) {
                result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                txtView.setText(result.get(0));
            }
        }
    }
    /**
     * Look up the default recognizer service in the preferences.
     * If the default have not been set then set the first available
     * recognizer as the default. If no recognizer is installed then
     * return null.
     */
    private ComponentName getServiceComponent() {
        String pkg = mPrefs.getString(getString(R.string.keyService), null);
        String cls = mPrefs.getString(getString(R.string.prefRecognizerServiceCls), null);
        if (pkg == null || cls == null) {
            List<ResolveInfo> services = getPackageManager().queryIntentServices(
                    new Intent(RecognitionService.SERVICE_INTERFACE), 0);
            if (services.isEmpty()) {
                return null;
            }
            ResolveInfo ri = services.iterator().next();
            pkg = ri.serviceInfo.packageName;
            cls = ri.serviceInfo.name;
            SharedPreferences.Editor editor = mPrefs.edit();
            editor.putString(getString(R.string.keyService), pkg);
            editor.putString(getString(R.string.prefRecognizerServiceCls), cls);
            editor.commit();
        }
        return new ComponentName(pkg, cls);
    }
    private android.speech.SpeechRecognizer speechRecognizer;
    private android.content.Context context;
}
